package com.tiance.shiro.filter;

import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.UserDO;
import com.tiance.domainservice.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 * 该过滤器用于在过滤器链的最后，对当前登录用户信息存入session和request中
 * Description：
 *
 * Modification History:
 *
 */

public class SessionFilter extends AccessControlFilter {

    @Autowired
    private UserService userService;
    /** logger */
    private static final Logger logger = LoggerFactory.getLogger(SessionFilter.class);


    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        if (subject == null) {
            // 没有登录
            return false;
        }
        HttpSession session = WebUtils.toHttp(request).getSession();
        Object sessionUsername = session.getAttribute(CommonConstants.USER);
        if (sessionUsername == null) {
            String principal =request.getParameter("userName");
            UserDO userDO=userService.queryUserByUserName(principal);
            request.setAttribute(CommonConstants.USER,userDO);
            session.setAttribute(CommonConstants.USER,userDO);

        }
        return true;
    }



    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return true;
    }



}
